<template>
  <div class="container">
    <div class="controls">
      <div class="search-container">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索文件名..." 
          class="search-input"
        />
        <img
          src="@/assets/picture/find.png" 
          class="search-icon" 
          @click="filterResources"
        />
      </div>
    </div>

    <table class="resource-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>资料名称</th>
          <th>收藏时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(resource, index) in paginatedResources" :key="resource.resource_id">
          <td>{{ (currentPage - 1) * itemsPerPage + index + 1 }}</td>
          <td>{{ resource.resource_name }}</td>
          <td>{{ resource.create_time }}</td>
          <td>
            <a class="btn btn-link" :href="resource.resource_url" target="_blank">下载</a>
            <button class="btn btn-view" @click="handleView(resource)">查看</button>
            <div class="favorite-icon" @click.stop="toggleFavorite(resource)">
              <img 
                :src="resource.isFavorite ? require('@/assets/picture/star-solid.png') : require('@/assets/picture/star.png')" 
                :alt="resource.isFavorite ? '已收藏' : '未收藏'" 
              />
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <PagiNation
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />

    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>


<script>
import { ref, computed, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import PagiNation from '@/components/PagiNation.vue';
import { fetchStudentResources } from '@/services/api';
import { addStudentFavorite, removeStudentFavorites } from '@/services/api';


export default {
  name: 'WordPage',
  components: {
    PagiNation,
  },
  setup() {
    const userId = ref(localStorage.getItem('id'));
    const router = useRouter();
    const techId = ref(null);
    const token = ref(null);
    const currentPage = ref(1);
    const itemsPerPage = 15; //条数
    const resources = ref([]);
    const filteredResources = ref([]);
    const searchQuery = ref('');
    const file = ref(null);
    const isLoading = ref(false); // Add loading state

    // Fetch only word resources
    const fetchResources = () => {
      if (!techId.value) {
        router.push('/login');
        return;
      }

      isLoading.value = true; // Start loading

      fetchStudentResources(techId.value, 'word')
        .then((response) => {
          if (response.data.status === 1) {
            resources.value = response.data.data.map(res => ({
              ...res,
              isFavorite: true,         // 后端是否收藏
              re_star_id: res.re_star_id || null
            }));
            filteredResources.value = resources.value;
            currentPage.value = 1;
          } else {
            console.error('获取资源失败:', response.data.msg);
            if (response.data.status === 'NOT_LOGIN') {
              router.push('/login');
            }
          }
        })
        .catch((error) => {
          console.error('请求错误:', error);
        })
        .finally(() => {
          isLoading.value = false; // End loading
        });
    };
    const handleView = (resource) => {
      const previewUrl = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(resource.resource_url)}`;
      window.open(previewUrl, '_blank');
    };
    const filterResources = () => {
      if (searchQuery.value) {
        filteredResources.value = resources.value.filter(resource =>
          resource.resource_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      } else {
        filteredResources.value = resources.value;
      }
      currentPage.value = 1; // Reset to the first page
    };

    const paginatedResources = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredResources.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredResources.value.length / itemsPerPage) || 1;
    });

    const toggleFavorite = async (res) => {
      if (res.isFavorite) {
        // 取消收藏
        try {
          const response = await removeStudentFavorites(res.re_star_id);
          if (response.data.status === 1) {
            res.isFavorite = false;
            res.re_star_id = null;
            ElMessage.success('取消收藏成功');
          } else {
            ElMessage.error('取消收藏失败');
          }
        } catch (error) {
          console.error('取消收藏失败:', error);
          ElMessage.error('网络错误，取消收藏失败');
        }
      } else {
        // 添加收藏
        try {
          const response = await addStudentFavorite({
            user_id: userId.value,
            resource_id: res.resource_id
          });
          if (response.data.status === 1) {
            res.isFavorite = true;
            // 若有返回 re_star_id 可赋值
            // res.re_star_id = response.data.data.re_star_id;
            ElMessage.success('收藏成功');
          } else {
            ElMessage.error('收藏失败');
          }
        } catch (error) {
          console.error('收藏失败:', error);
          ElMessage.error('网络错误，收藏失败');
        }
      }
    };

    onMounted(() => {
      const storedTechId = localStorage.getItem('id');
      const storedToken = localStorage.getItem('token');

      if (storedTechId && storedToken) {
        techId.value = storedTechId;
        token.value = storedToken;
        fetchResources();
      } else {
        console.error('User is not logged in. Redirecting to login page.');
        router.push('/login');
      }
    });

    return {
      techId,
      token,
      currentPage,
      itemsPerPage,
      resources,
      filteredResources,
      paginatedResources,
      searchQuery,
      toggleFavorite,
      removeStudentFavorites,
      addStudentFavorite,
      filterResources,
      totalPages,
      isLoading,
      file,
      handleView
    };
  },
};
</script>

<style scoped>
.favorite-icon {
  display: inline-block;
  margin-left: 8px;
  background-color: white;
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.favorite-icon img {
  width: 16px;
  height: 16px;
}


.container {
  padding: 20px;
  margin-bottom: 40px;
}
.resource-table input[type="text"] {
  width: 100%;
  padding: 5px;
  font-size: 14px;
}


.resource-table td:nth-child(1) { width: 7%; }
.resource-table td:nth-child(2) { width: 38%; }
.resource-table td:nth-child(3) { width: 30%; }
.resource-table td:nth-child(4) { width: 25%; }
.controls {
  display: flex; /* Use flexbox */
  justify-content: space-between; 
  align-items: center; /* Vertically center */
  margin-bottom: 20px;
}

.btn  {
  display: inline-block;
  padding: 8px 10px;
  margin: 5px;
  background-color: rgb(236, 241, 253);
  color: #82beff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #badafc;
  color: rgb(0, 110, 255);
}

.btn-upload  {
  background-color: #125AA2;
  color: #fff;
}

.btn-upload:hover {
  background-color: #3987d4;
  color: white;
}


.filter-container {
  display: flex;
  gap: 10px;
}

.filter-text{
  margin-right: 10px;
  cursor: pointer;
  font-weight: normal;
  padding-bottom: 10px;
  width: 90px;
  text-align: center;
  color: #4d4d4d;
}

.filter-text.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
  margin-bottom: -2px;
}
.search-container {
  display: inline-flex;
  align-items: center;
  margin-left: auto; /* Push the search container to the right */
  position: relative; /* 用于定位搜索图标 */
}

.search-input {
  padding: 10px 40px 10px 10px; /* 给右边留出空间放图标 */
  border: 1px solid #ccc;
  border-radius: 20px; /* 设置圆角 */
  font-size: 16px;
  width: 200px; /* Set search box width */
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}


.resource-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
}

.resource-table th{
  padding: 10px;
}

.resource-table th,
.resource-table td {
  text-align: center; /* 设置文本居中 */
  border: 1px solid #ddd;
  font-size: 14px;
  color: #4d4d4d;
}

.resource-table th {
  background-color: #f4f4f4;
  color: #333;
  font-weight: bold;
  font-size: 14px;
  color: #4d4d4d;
}

.resource-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.resource-table tbody tr:hover {
  background-color: #e9ecef;
}

.resource-table a {
  text-decoration: none;
}
.btn-link{
background-color: #3A88D5;
color: white;
}
.resource-edit-input {
  width: 100%;
  padding: 5px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box; /* 包含内边距和边框在宽度计算中 */
}

/* Pagination */
.pagination {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination .btn {
  padding: 8px 12px;
  margin: 0 10px;
  cursor: pointer;
  border: none;
  background-color: #2196f3;
  color: white;
  border-radius: 4px;
}

.pagination .btn:disabled {
  background-color: #b0c4de;
  cursor: not-allowed;
}

.pagination span {
  margin: 0 10px;
  font-weight: bold;
}

/* Loading indicator */
.loading {
  text-align: center;
  font-size: 18px;
  color: #555;
  margin-top: 20px;
}
</style>

